<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<script type="text/javascript">
	//涉及jquery和WebSocket知识点，见文档
	var hostname = 'broker.hivemq.com', port = 8000, clientId = $.cookie("SESSIONID"), timeout = 5, keepAlive = 50, cleanSession = false, ssl = false, userName = 'admin';
	password = 'password', subscribe_topic = "fjjxu/19/device/#", publish_topic = "fjjxu/19/device/";
	client = new Paho.MQTT.Client(hostname, port, clientId);
	var options = {
		invocationContext : {
			host : hostname,
			port : port,
			path : client.path,
			clientId : clientId
		},
		timeout : timeout,
		keepAliveInterval : keepAlive,
		cleanSession : cleanSession,
		useSSL : ssl,
		userName : userName,
		password : password,
		onSuccess : onConnect,
		onFailure : function(e) {
			$("#statusbar").attr("class", "alert alert-warning");
			$("#statusbar").text("连接MQTT服务器失败！ ");
		}
	};
	function onConnect() {
		$("#statusbar").attr("class", "alert alert-info");
		$("#statusbar").text("连接MQTT服务器成功！ ");
		client.subscribe(subscribe_topic, {
			qos : 0
		});
		console.log("MQTT主题 "+subscribe_topic+" 订阅成功！");//此处为订阅
	}
	client.onConnectionLost = onConnectionLost;
	//注册连接断开处理事件
	client.onMessageArrived = onMessageArrived;
	//注册消息接收处理事件
	function onConnectionLost(responseObject) {
		console.log(responseObject);
		if (responseObject.errorCode !== 0) {
			console.log("onConnectionLost:" + responseObject.errorMessage);
			$("#statusbar").attr("class", "alert alert-warning");
			$("#statusbar").text("与MQTT服务器连接已断开！ ");
		}
	}
	function onMessageArrived(message) {
		//收到的消息在这里处理
		console.log("收到消息:" + message.payloadString);
		var datajson = JSON.parse(message.payloadString);
		var sendData = JSON.parse(JSON.stringify(datajson.data));
		$.ajax({//异步保存到数据库
			type : "post",
			url : "HistoryDataServlet?action=add",
			data : sendData,
			dataType:"json", 
	        contentType:"application/json;charset=utf-8", 
			success : function(data) {
				console.log("add OK. And msg: "+data);
			},
			error : function(result) {
				$("#statusbar").attr("class", "alert alert-warning");
				$("#statusbar").text("数据库服务器的消息发送意外中断！ ");
			}
		});
		switch(datajson.device){
		case "RGBLED":
				var rgbled = $.parseJSON(datajson.data);
				if (rgbled.power == "on") {
					$('#ledswitch').bootstrapSwitch('state', true);
					//根据回传的设备数据切换页面的开关控件的开关状态
				} else {
					$('#ledswitch').bootstrapSwitch('state', false);
					$("#led").attr("class", "off");
					break;
				}
				//console.log(rgbled.color);
				$("#led").attr("class", rgbled.color);
				//id为led元素的class属性为回传设备数据中的颜色信息。
			break;
		case "DHT11":
			if($('#dataswitch').is(':checked')) {
				var dht11 = $.parseJSON(datajson.data);
				humiindicator.animate(dht11.humi);
				tempindicator.animate(dht11.temp);
				//存储历史数据
			}
			break;
			<% boolean flag = true;
			String type = "Hello";
			if(flag){//改为for循环，遍历所有需要显示的设备
			%>
		case <%=type%>:
			console.log("Hello!");
			break;
		<% }%>
		default:
			console.log("出现无法解析的设备类型："+datajson.device);
			break;
		};
	}
	
	function mqttsend(type, dataJson) {
		var jsonRaw = {
			device: type,
			time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
			data: JSON.stringify(dataJson),
			clientId: clientId
		};
		message = new Paho.MQTT.Message(JSON.stringify(jsonRaw));
		message.destinationName = publish_topic + type;
		client.send(message);
	}
	
	var refreshtimer;
	function refresh() { //请求获取设备的实时信息。
		$.ajax({
			type : "post",
			url : "HistoryDataServlet?action=last",
			success : function(data) {
				console.log("send OK. And last data: " + data);
				jsondata = JSON.parse(data);
				humiindicator.animate(jsondata.humi);
				tempindicator.animate(jsondata.temp);
			},
			error : function(result) {
				$("#statusbar").attr("class", "alert alert-warning");
				$("#statusbar").text("连接数据库服务器失败！ ");
			}
		});
	}
	var humiindicator;
	var tempindicator;
	$(document).ready(function() { // 出处（jQuery语法），文档加载后执行

		client.connect(options);
		$('#dataswitch').bootstrapSwitch(); //初始化开关控件
		$('#dataswitch').on('switchChange.bootstrapSwitch',
				function(event, state) {
					//控件状态改变时触发
					//alert(state);
				});
		$('#ledswitch').bootstrapSwitch(); //初始化开关控件
		$('#ledswitch').on('switchChange.bootstrapSwitch',
				function(event, state) {
					//控件状态改变时触发
					//alert(state);
				});
		//$('#ledswitch').bootstrapSwitch('state',false); //设置开关控件的开/关状态的方法
		//radialIndicator是一款轻量级的jQuery圆形进度指示器插件。该圆形指示器插件支持颜色范围，动态修改值，格式化和百分比值等形式。 http://www.htmleaf.com/jQuery/Layout-Interface/201502171389.html
		$('#humi').radialIndicator({
			//设置环形进度条（圆形指示器） ， 不同的百分比提供不同的颜色							
			barColor : "#87CEEB",
			barWidth : 10,
			initValue : 40,
			roundCorner : true,
			percentage : true, //设置为true显示环形进度条的百分比数值。
			interpolate : true,//允许环形进度条内部允许嵌入内容
		});
		humiindicator = $('#humi').data('radialIndicator');//获取进度条数据
		//console.log(progObj.current_value);
		//console.log(progObj);控制面板输出
		$('#temp').radialIndicator({
			barColor : {
				0 : '#87CEEB',
				30: '#FF7F27',
				100 : '#FF0000',
				200 : '#050000',
			},
			barWidth : 10,
			initValue : 100,
			roundCorner : true,
			minValue : -100,
			maxValue : 200,
			interaction: false,
			interpolate: true,
			format: '###°C'
		});
		tempindicator = $('#temp').data('radialIndicator'); //获取进度条数据
		humiindicator.animate(80);
		tempindicator.animate(140);
		
		//单击页面的按钮发送相应的控制指令
		$("#ledr").click(function() {
			var dataJson = {
				power: "on",
				color: "r"
			};
			mqttsend("RGBLED", dataJson);
		});
		$("#ledg").click(function() {
			var dataJson = {
				power: "on",
				color: "g"
			};
			mqttsend("RGBLED", dataJson);
		});
		$("#ledb").click(function() {
			// MQTT数据发送
			var dataJson = {
				power: "on",
				color: "b"
			};
			mqttsend("RGBLED", dataJson);
		});
	});
	// 预置方法
	Date.prototype.Format = function(fmt) {
		var o = {
			"M+" : this.getMonth() + 1, //月份
			"d+" : this.getDate(), //日
			"h+" : this.getHours(), //小时
			"m+" : this.getMinutes(), //分
			"s+" : this.getSeconds(), //秒
			"q+" : Math.floor((this.getMonth() + 3) / 3), 
			"S" : this.getMilliseconds()
		//毫秒
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
					.substr(4 - RegExp.$1.length));
		for ( var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
						: (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	};
	String.format = function() {
		var s = arguments[0];
		for (var i = 0; i < arguments.length - 1; i++) {
			var reg = new RegExp("\\{" + i + "\\}", "gm");
			s = s.replace(reg, arguments[i + 1]);
		}
		return s;
	};
</script>